// pages/emergency/emgResponseDetail/emgResponseDetail.js
var app = getApp()
var util = require('../../../utils/util.js')
import Dialog from '../../../dist/dialog/dialog.js';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        active: 0,
        emerData: {},//应急响应的基本信息,
        dutyList: [],//值班列表,
        emgWorkBriefList: [],//工作简报
        latelyReportTime: new Date(),//最近一次上班时间，没有上报过就是应急的发布时间
        page:1,
        reachBottom:false,
        selectPersonDialog:true,
        searchName:'',
        nameArray:[],//

        addDutyModal:true,
        dutySelectStr:'',//值班选择日期
        selectPhone:'',//长号
        selectPhoneShort:'',//短号
        applyUserId:0,//值班人的id
        applyUserName:'',//值班人名字,
        dutyDate:new Date(),
    },
    onChange:function(e){
        this.setData({
            active:e.detail.index
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var emerData = JSON.parse(options.emgResponse)
        emerData.signDateStr = util.formatTimeHour(new Date(emerData.signDate))
        this.setData({
            emerData: emerData
        })
        this.loadDutyList()
        this.loadWorkBriefList()
        var header;

        header = {
            'Cookie': wx.getStorageSync("sessionid"),//读取cookie
            'content-type': 'application/json'
        };
        var params={
            topTypeId: 264,
            typeId: 269,
            pageCurrent: 1,
            pageSize: 8
        }
        wx.request({
            url:app.globalData.baseUrl+'/safe/emgHandle/find',
            header:header,
            method:'POST',
            data:params,
            success(res){
                if(res.data.success){

                }
            }
        })
    },

    /**
     * 返回首页
     */
    backEmgResponseList(){
        wx.redirectTo({
            url:'/pages/emergency/emgResponse/emgResponse'
        })
    },

    /**
     * 加载值班列表
     */
    loadDutyList() {
        var that = this
        var header;
        header = {
            'Cookie': wx.getStorageSync("sessionid") //读取cookie
        };
        var params = {
            planPublicId: this.data.emerData.startPlanId,//启动的id
            companyId: app.globalData.user.companyId,
            pageSize:100
        }
        wx.request({
            header: header,
            url: app.globalData.baseUrl + '/safe/duty/find',
            method: "GET",
            data: params,
            success(res) {
                if (res.data.success) {
                    var dutyList=res.data.data.list
                    for(var i=0;i<dutyList.length;i++){
                        dutyList[i].dutyDateStr=util.formatTime(new Date(dutyList[i].dutyDate))
                    }
                    that.setData({
                        dutyList: dutyList
                    })
                }
            }
        })
    },

    /**
     * 加载工作简报
     */
    loadWorkBriefList() {
        var that = this
        this.setData({
            page:1,
            reachBottom:false
        })
        var header;
        header = {
            'Cookie': wx.getStorageSync("sessionid"), //读取cookie
            'content-type': 'application/x-www-form-urlencoded'

        };
        var params = {
            planPublicId: this.data.emerData.id,
            companyId: app.globalData.user.companyId,
            // sortField:'status',
            // sortOrder:'asc',
        }
        wx.request({
            header: header,
            url: app.globalData.baseUrl + '/safe/workBrief/find',
            method: "GET",
            data: params,
            success(res) {
                if (res.data.success) {
                    var dutyList = res.data.data.page.list
                    for (var i = 0; i < dutyList.length; i++) {
                        var reportTimeStr;
                        if (dutyList[i].status == 0) {
                            reportTimeStr = util.formatTimeHour(new Date())
                            dutyList[i].reportTimeStr = reportTimeStr
                            dutyList[i].statusStr = "未发布"
                        } else {
                            reportTimeStr = util.formatTimeHour(new Date(dutyList[i].reportTime))
                            dutyList[i].reportTimeStr = reportTimeStr
                            dutyList[i].statusStr = "已发布"
                        }
                    }
                    if(res.data.data.page.isLastPage){
                        that.setData({
                            reachBottom:true
                        })
                    }
                    that.setData({
                        emgWorkBriefList: res.data.data.page.list
                    })
                }
            }
        })
    },
    /**
     * 查看简报详情
     * @param e
     */
    workBriefDetail(e) {
        wx.navigateTo({
            url: '/pages/emergency/workBriefAdd/workBriefAdd?add=false&workBrief='
            + JSON.stringify(this.data.emgWorkBriefList[e.currentTarget.dataset.index])
        })
    },
    /**
     * 添加工作简报
     * @param e
     */
    addWorkBrief(e) {
        wx.navigateTo({
            url: '/pages/emergency/workBriefAdd/workBriefAdd?add=true&emgPlanPublicId=' + this.data.emerData.startPlanId
        })
    },
    /**
     * 值班日期选择
     */
    dutyDataSelect(e){
        console.log('picker发送选择改变，携带值为', e.detail.value)

        this.setData({
            dutySelectStr: e.detail.value,
            deadline:e.detail.value
        })
    },
    addDutyModal(){
      this.setData({
          selectPersonDialog:false,
          deadline:util.formatTime(new Date()),
          dutyDate:new Date()
      })
    },
    /**
     * 添加值班
     */
    addDuty(){
        var that=this

        if(!this.data.dutySelectStr||this.data.applyUserId==0){
            wx.showToast({
              title: '人员和值班日期不能为空'

            })
        }else{
            var header;

            header = {
                'Cookie': wx.getStorageSync("sessionid"),//读取cookie
                'content-type': 'application/x-www-form-urlencoded'
            };
            var params={
                planPublicId:this.data.emerData.startPlanId,
                companyId:app.globalData.user.companyId,
                dutyDate:new Date(that.data.dutySelectStr),
                name:this.data.applyUserName,
                userId:this.data.applyUserId,
                phone:this.data.selectPhone,
                shortPhone:this.data.selectPhoneShort,
            }
            wx.request({
                url:app.globalData.baseUrl+'/safe/duty/add',
                header:header,
                method:'POST',
                data:params,
                success(res){
                    if(res.data.success){
                        var dutyList=that.data.dutyList
                        var duty=res.data.data
                        duty.dutyDateStr=util.formatTime(new Date(duty.dutyDate))
                        dutyList.push(duty)
                        that.setData({
                            dutyList:dutyList,
                            selectPersonDialog:true
                        })
                    }else{
                        wx.showToast({
                          title: '添加值班记录失败'
                        })
                    }
                }
            })
        }
    },
    /**
     * 删除值班
     */
    deleteDuty(e){
        var dutyId=parseInt(e.currentTarget.dataset.dutyid)
        var index=e.currentTarget.dataset.index
        var that=this
        Dialog.confirm({
            title:'删除提示',
            message:'是否删除改值班',
            selector:'#van-dialog',
        }).then(()=>{
            var header;

            header = {
                'Cookie': wx.getStorageSync("sessionid"),//读取cookie
                'content-type': 'application/x-www-form-urlencoded'
            };
            var params={id:dutyId}
            wx.request({
                url:app.globalData.baseUrl+'/safe/duty/delete',
                header:header,
                method:'POST',
                data:params,
                success(res){
                    if(res.data.success){
                        var dutyList=that.data.dutyList
                        dutyList.splice(index,1)
                        that.setData({
                            dutyList:dutyList
                        })
                    }else{
                        wx.showToast({
                          title: '删除失败'
                        })
                    }
                }
            })
        })
    },

    /**
     * 搜索人员响应
     */
    searchNameClick(val){
        this.setData({
            searchName: val.detail,

        })
        this.searchName();
    },
    /**
     * 记录搜索人员
     */
    onSearchNameChange(val){
        this.setData({
            searchName: val.detail
        })
    },
    /**
     * 搜索人民
     */
    searchName() {
        var that = this;
        var header;
        header = {
            'Cookie': wx.getStorageSync("sessionid") //读取cookie
        };
        wx.request({
            header: header,
            url: app.globalData.baseUrl + '/safe/user/find',
            method: 'get',
            data: { username: this.data.searchName, pageSize:5},
            success(res) {
                var tempList = [];
                for (var i = 0; i < res.data.data.list.length; i++) {
                    tempList.push({ userId: res.data.data.list[i].userId,
                        mobile:res.data.data.list[i].mobile,
                        shortPhone:res.data.data.list[i].shortPhone,
                        userName: res.data.data.list[i].username });
                }
                that.setData({
                    nameArray: tempList
                })
            }
        })
    },
    /**
     * 点击选择人员
     */
    nameClick(item){
        this.setData({
            applyUserName: item.target.dataset.username,
            applyUserId: item.target.dataset.userid,
            selectPhone:item.target.dataset.mobile,
            selectPhoneShort:item.target.dataset.shortphone,
            searchName:item.target.dataset.username,
        })
    },
    /**
     * 关闭人员选择弹出框
     */
    hiddenPersonDialog(){
        this.setData({
            selectPersonDialog: true,
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.loadWorkBriefList()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        if(this.data.active!=1){
            return;
        }
        var that = this;
        // 显示加载图标
        wx.showLoading({
            title: '玩命加载中',
        })
        var header;
        header = {
            'Cookie': wx.getStorageSync("sessionid"), //读取cookie
            'content-type': 'application/x-www-form-urlencoded'

        };
        var params = {
            pageCurrent: this.data.page + 1,
            companyId:app.globalData.user.companyId,
            planPublicId:this.data.emerData.startPlanId,
            pageSize:10,
            sortField:'status',
            sortOrder:'asc',
        }
        wx.request({
            header: header,
            url: app.globalData.baseUrl + '/safe/workBrief/find',
            method: "GET",
            data: params,
            success(res) {
                console.log(res)
                wx.hideLoading()
                if (that.data.reachBottom) {
                    wx.showToast({
                        title: '没有更多数据',
                    })
                }else{
                    if (res.data.success) {
                        var dutyList = res.data.data.page.list
                        var oldWorkBriefList=that.data.emgWorkBriefList
                        for (var i = 0; i < dutyList.length; i++) {
                            var reportTimeStr = util.formatTimeHour(new Date(dutyList[i].reportTime))
                            dutyList[i].reportTimeStr = reportTimeStr
                            if (dutyList[i].status == 0) {
                                dutyList[i].statusStr = "未发布"
                            } else {
                                dutyList[i].statusStr = "已发布"
                            }
                            oldWorkBriefList.push(dutyList[i])
                        }
                        that.setData({
                            emgWorkBriefList: oldWorkBriefList
                        })
                        if(res.data.data.page.isLastPage){
                            that.setData({
                                reachBottom: true
                            })
                        }
                    }
                }
            }
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})